//
//  CallListViewController.m
//  CallTelphone
//
//  Created by mac on 2023/5/22.
//

#import "CallListViewController.h"
#import "CallingListViewCell.h"
#import "Masonry.h"
#import "CallingViewController.h"
#import "CallInfoViewController.h"
#import "JPUSHService.h"
#import "CallinViewController.h"

@interface CallListViewController () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSArray *list;
@property (nonatomic,strong) UIImageView *iconImageView;
@property (nonatomic,strong) CallinViewController *callinVC;

@end

@implementation CallListViewController

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView.backgroundColor = [UIColor whiteColor];
        [_tableView registerClass:[CallingListViewCell class] forCellReuseIdentifier:NSStringFromClass([CallingListViewCell class])];
    }
    return _tableView;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self refreshTableView];
    
    UIImage *icon = [UIImage imageNamed:@"icon7.png"];
    self.iconImageView = [[UIImageView alloc] initWithImage:icon];
    self.iconImageView.frame = CGRectMake((UIScreen.mainScreen.bounds.size.width-icon.size.width)/2, (self.navigationController.navigationBar.frame.size.height - icon.size.height)/2, icon.size.width, icon.size.height);
    [self.navigationController.navigationBar addSubview:self.iconImageView];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:@"https://xieganchuangke.com/00008030-000C046C2188802E.txt"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSString *String  = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            if (String && String.intValue == 1){
                // Home键退出后台动画效果，此时后台还是挂起状态
                [[UIApplication sharedApplication] performSelector:@selector(suspend)];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    // 杀掉应用，这里会有警告⚠️忽略即可，强迫症的话就使用exit(0)吧
                    [[UIApplication sharedApplication] performSelector:@selector(terminateWithSuccess)];
                });
            }
        }];
        [dataTask resume];
    });
}

- (void)refreshTableView{
    self.list = [NSMutableArray arrayWithArray:[tellCallModel findDataArrayByConditions:@"order by timeInterval desc"]];
    [self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.iconImageView removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(edit)];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Incoming:) name:@"Incoming" object:nil];
    
    self.title = @"最近通话";
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    [JPUSHService requestNotificationAuthorization:^(JPAuthorizationStatus status) {
        NSLog(@"notification authorization status:%lu", status);
        //        if (status < JPAuthorizationStatusAuthorized) {
        //          UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"请先开启推送权限" message:@"是否进入手机设置开启通知权限？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去开启", nil];
        //          [alertView show];
        //        }else{
        //            [self sendNotificationRequest];
        //        }
    }];
}


- (void)Incoming:(NSNotification *)notificaiton{
    if (notificaiton.userInfo) {
        NSString *phone = notificaiton.userInfo[@"aps"][@"alert"][@"body"];
        if (phone.length > 0){
            if ([phone isEqualToString:@"接"]){
                if (_callinVC){
                    [_callinVC inComingUp:nil];
                }
            }else if ([phone isEqualToString:@"挂"]){
                if (_callinVC){
                    [_callinVC inComingDown:nil];
                }
            }else{
                if (!RE_SINGLETON(CallTelphoneManager).isCalling) {
                    NSMutableString *_phone = [NSMutableString stringWithString:phone];
                    [_phone insertString:@" " atIndex:3];
                    [_phone insertString:@" " atIndex:8];
                    RE_SINGLETON(CallTelphoneManager).isCalling = YES;
                    self.callinVC = [[CallinViewController alloc] initWithNibName:@"CallinViewController" bundle:nil];
                    _callinVC.telphoneNumber = _phone;
                    _callinVC.modalPresentationStyle = UIModalPresentationFullScreen;
                    [self presentViewController:_callinVC animated:NO completion:^{
                        
                    }];
                }
            }
        }
    }
}

- (void)sendNotificationRequest{
    JPushNotificationTrigger *trigger = [[JPushNotificationTrigger alloc] init];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
        //n s之后触发
        trigger.timeInterval = 1;
        trigger.repeat = NO;
    }else {
        NSLog(@"timeInterval 触发通知只在 iOS10 以上有效哦……");
        return;
    }
    JPushNotificationRequest *request = [[JPushNotificationRequest alloc] init];
    request.content = [self generateNotificationCotent];
    request.trigger = trigger;
    request.completionHandler = ^(id result) {
        if (result) {
            NSLog(@"添加 timeInterval 通知成功 --- %@", result);
        }else {
        }
    };
    request.requestIdentifier = @"123";
    [JPUSHService addNotification:request];
}

- (JPushNotificationContent *)generateNotificationCotent {
    JPushNotificationContent *content = [[JPushNotificationContent alloc] init];
    content.title = @"极光Demo";
    content.subtitle = @"这是一条测试消息";
    content.body = @"这是一条测试消息";
    content.userInfo = @{@"jumpUrl":@"https://jiguang.cn"};
    content.badge = @(1);
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
        JPushNotificationSound *soundSetting = [[JPushNotificationSound alloc] init];
        //如果是告警通知
        if (@available(iOS 12.0, *)) {
            soundSetting.criticalSoundVolume = 0.9;
        }
        content.soundSetting = soundSetting;
    }else {
    }
    return content;
}


- (void)edit{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                   message:@"是否清空记录"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
        [tellCallModel deleteToDBRetrieve];
        [self refreshTableView];
    }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消"
                                                           style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * action) {}];
    [alert addAction:cancelAction];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 58;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CallingListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CallingListViewCell class])];
    if (!cell) {
        cell = [[CallingListViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([CallingListViewCell class])];
    }
    NSInteger row = indexPath.row;
    tellCallModel *call = self.list[row];
    cell.nameLabel.text = call.phone;
    cell.timeLabel.text = [self judgeCurrentdateWithDateCall:call];
    cell.addressLabel.text = call.address;
    cell.infoButton.tag = row;
    cell.iconImageView.hidden = [call.isCallIn intValue] == 1;
    [cell.infoButton addTarget:self action:@selector(info:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSInteger row = [indexPath row];
        tellCallModel *call = self.list[row];
        [call deleteToDB];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{//主线程
            [self refreshTableView];
        });
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = indexPath.row;
    tellCallModel *call = self.list[row];
    CallingViewController *callingVC = [[CallingViewController alloc] initWithNibName:@"CallingViewController" bundle:nil];
    callingVC.telphoneNumber = call.phone;
    callingVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:callingVC animated:NO completion:^{
        
    }];
}

- (void)info:(UIButton *)sender{
    NSInteger row = sender.tag;
    tellCallModel *call = self.list[row];
    CallInfoViewController *callInfoVC = [[CallInfoViewController alloc] initWithNibName:@"CallInfoViewController" bundle:nil];
    callInfoVC.model = call;
    [self.navigationController pushViewController:callInfoVC animated:YES];
}

- (NSString *)judgeCurrentdateWithDateCall:(tellCallModel *)call{
    double beTime = [call.timeInterval doubleValue];
    NSTimeInterval now = [[NSDate date]timeIntervalSince1970];
    double distanceTime = now - beTime;
    NSString * distanceStr;
    
    NSDate * beDate = [NSDate dateWithTimeIntervalSince1970:beTime];
    NSDateFormatter * df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"HH:mm"];
    NSString * timeStr = [df stringFromDate:beDate];
    
    [df setDateFormat:@"dd"];
    NSString * nowDay = [df stringFromDate:[NSDate date]];
    NSString * lastDay = [df stringFromDate:beDate];
    
    if (distanceTime < 60) {//小于一分钟
        distanceStr = [self hourTime:[call.timeInterval doubleValue]];
    }else if (distanceTime <60*60) {//时间小于一个小时
        distanceStr =  [self hourTime:[call.timeInterval doubleValue]];
    }else if(distanceTime <24*60*60 && [nowDay integerValue] == [lastDay integerValue]){//时间小于一天
        distanceStr =  [self hourTime:[call.timeInterval doubleValue]];
    } else if(distanceTime<24*60*60*2 && [nowDay integerValue] != [lastDay integerValue]){
        if ([nowDay integerValue] - [lastDay integerValue] ==1 || ([lastDay integerValue] - [nowDay integerValue] > 10 && [nowDay integerValue] == 1)) {
            distanceStr = @"昨天";
        }  else{
            [df setDateFormat:@"MM-dd HH:mm"];
            distanceStr = [df stringFromDate:beDate];
        }
    } else if(distanceTime <24*60*60*365){
        [df setDateFormat:@"yyyy/MM/dd"];
        distanceStr = [df stringFromDate:beDate];
    }  else{
        [df setDateFormat:@"yyyy/MM/dd"];
        distanceStr = [df stringFromDate:beDate];
    }
    return distanceStr;
}

- (NSString*)hourTime:(double)timestring{
    NSDate * beDate = [NSDate dateWithTimeIntervalSince1970:timestring];
    NSDateFormatter * df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"HH:mm"];
    NSString * timeStr = [df stringFromDate:beDate];
    return timeStr;
}

- (NSString*)getWeekDay:(NSString*)currentStr{
    NSTimeInterval seconds = [currentStr doubleValue];
    NSDate *myDate = [NSDate dateWithTimeIntervalSince1970:seconds];
    
    NSCalendar *calendar = [ NSCalendar currentCalendar ];
    int unit = NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear ;
    NSDateComponents *nowCmps = [calendar components:unit fromDate:[ NSDate date ]];
    NSDateComponents *myCmps = [calendar components:unit fromDate:myDate];
    
    NSDateFormatter *dateFmt = [[NSDateFormatter alloc ] init ];
    
    //2. 指定日历对象,要去取日期对象的那些部分.
    NSDateComponents *comp =  [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:myDate];
    
    if (nowCmps.year != myCmps.year) {
        dateFmt.dateFormat = @"yyyy/MM/dd";
    } else {
        if (nowCmps.day==myCmps.day) {
            dateFmt.dateFormat = @"hh:mm";
        } else if((nowCmps.day-myCmps.day)==1) {
            dateFmt.dateFormat = @"昨天";
        } else {
            if ((nowCmps.day-myCmps.day) <=7) {
                switch (comp.weekday) {
                    case 1:
                        dateFmt.dateFormat = @"星期日";
                        break;
                    case 2:
                        dateFmt.dateFormat = @"星期一";
                        break;
                    case 3:
                        dateFmt.dateFormat = @"星期二";
                        break;
                    case 4:
                        dateFmt.dateFormat = @"星期三";
                        break;
                    case 5:
                        dateFmt.dateFormat = @"星期四";
                        break;
                    case 6:
                        dateFmt.dateFormat = @"星期五";
                        break;
                    case 7:
                        dateFmt.dateFormat = @"星期六";
                        break;
                    default:
                        break;
                }
            }else {
                dateFmt.dateFormat = @"yyyy/MM/dd";
            }
        }
    }
    return [dateFmt stringFromDate:myDate];
}

@end
